#include <stdio.h>
#include <string.h>
#include <assert.h>
//char* strncpy(char* destination, const char* source, size_t num)
//可以指定拷贝几个字节,相对安全.
//num大于源字符串字符个数时，多余的空间全部拷贝'\0';
//strncat, strncmp同理
//strncpy中num小于目标字符串长度时不会加上'\0',大于时会加上'\0'
//strncat无论追加多少，都会加上'\0'。且num大于源字符串长度时只会追加一个'\0'
//模拟实现

int my_strncmp(const char* str1, const char* str2, size_t num)
{
    assert(str1 && str2);
    while(*str1 == *str2 && num--)
    {
        if(*str1 == '\0')
        return 0;
        str1++;
        str2++;
    }
    return (*str1 - *str2);
}

char* my_strncat(char* dest, const char* src, size_t num)
{
    assert(dest && src);
    char* ret = dest;
    while(*dest != '\0')
    {
        dest++;
    }
    while(num--)
    {
        *dest++ = *src++;
        if(*src == '\0')
        break;
    }
    *dest = '\0';
}

char* my_strncpy(char* dest, const char* src, size_t num)
{
    assert(dest && src);
    char* ret = dest;
    int flag = 0;
    while(num--)
    {
        if(*dest == '\0')
        flag = 1;
        if(*src == '\0')
        *dest++ = *src;
        else
        *dest++ = *src++;
    }
    if(flag)
    *dest = '\0';
    return ret;
}

int main()
{
    //char arr1[20] = "abcdef";
    //char arr2[] = "bit";
    //my_strncpy(arr1, arr2, 5);
    //printf("%s\n", arr1);
    //my_strncat(arr1, arr2, 3);
    //printf("%s\n", arr1);

    char arr1[20] = "abcxxx";
    char arr2[] = "defg";
    strncpy(arr1, arr2, 2);
    printf("%s\n", arr1);
    strncpy(arr1, arr2, 5);
    printf("%s\n", arr1);

    return 0;
}